package com.abc.robot01.activity

import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.activity.viewModels
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.layout.wrapContentWidth
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicText
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.RectangleShape
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Popup
import androidx.navigation.ui.AppBarConfiguration
import com.abc.robot01.R
import com.abc.robot01.activity.FangAnKuActivity.Companion
import com.abc.robot01.databinding.ContentMain3Binding
import com.abc.robot01.retrofit.bean.DataB
import com.abc.robot01.retrofit.bean.HouseType
import com.abc.robot01.view.enableFaClick
import com.abc.robot01.view.enableHomeClick
import com.abc.robot01.view.enableInfoClick
import com.abc.robot01.view.enableSpClick
import com.abc.robot01.vivemodel.ShangPinKuViewModel
import com.bumptech.glide.integration.compose.ExperimentalGlideComposeApi
import com.bumptech.glide.integration.compose.GlideImage


/**
 * 商品库
 */
class ShangPinKuActivity : BaseVoiceActivity() {
    private lateinit var binding: ContentMain3Binding
    private val viewModel: ShangPinKuViewModel by viewModels()

    override fun handleVoiceCommand(asr: String): Boolean {
        if(asr.contains("商品")) {
            return true
        } else
            if(asr.contains("信息")) {
                startActivity<SysMessageActivity> { }
                playTTS("好的")
                finish()
                return true
            }
            else
                if(asr.contains("方案")) {
                    startActivity<FangAnKuActivity> { }
                    playTTS("好的")
                    finish()
                    return true
                }
                else
                    if(asr.contains("首页")) {
                        playTTS("好的")
                        finish()
                        return true
                    }
        return false
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Log.e(TAG, "onCreate");
        binding = ContentMain3Binding.inflate(layoutInflater);
        setContentView(binding.root)

        enableSpClick(){
        }

        enableInfoClick(){
            finish()
            startActivity<SysMessageActivity>()
        }

        enableFaClick {
            finish()
            startActivity<FangAnKuActivity>()
        }

        enableHomeClick(){
            finish()
        }

        binding.composeView.setContent {
            val showPopup = remember { viewModel.showPopup}
            Box(
                modifier = Modifier.fillMaxSize()
            ) {
                // 背景图片
                Image(
                    painter = painterResource(id = R.drawable.z1), // 替换为你的图片资源ID
                    contentDescription = null,
                    contentScale = ContentScale.Crop, // 使图片填充整个背景
                    modifier = Modifier.matchParentSize() // 使图片铺满整个Box
                )
                Column(
                ) {
                    Spacer(modifier = Modifier.height(30.px))
                    BasicText(
                        text = "商品库",
                        style = TextStyle(
                            fontWeight = FontWeight.Bold,
                            fontSize = 10.sp,
                            color = MYBLACK
                        ),
                        modifier = Modifier
                            .offset(x = 30.px)
//                        .padding((30 / 3.5f).dp)
//                            .clickable {
//                                Log.e(TAG, "" + 8.sp.value);
//                            }
                    )
                    Spacer(modifier = Modifier.height(30.px))
                    Row {

                        RowWithShapeBox()
                        Spacer(modifier = Modifier.width(15.dp))
                        CustomStyledTextField(placeHolder = "请输入关键词搜索"){
                                        viewModel.loadMoreData(name = it)
                        }
                        Spacer(modifier = Modifier.width(26.px))
                        Box(modifier = Modifier
                            .align(Alignment.CenterVertically)
                            .clickable {
                                showPopup.value = showPopup.value.not()
                            }) {
                            Row {
                                BasicText(
                                    modifier = Modifier.align(Alignment.CenterVertically),
                                    text = "更多筛选",
                                    style = TextStyle(
                                        fontSize = MyFont_Size,
                                        color = Color.Black
                                    ),
//                        .padding((30 / 3.5f).dp)
//                            .clickable {
//                                Log.e(TAG, "" + 8.sp.value);
//                            }
                                )
                                Spacer(modifier = Modifier.width(10.px))
                                Image(
                                    painter = painterResource(R.drawable.arrow_down), // Replace with your image resource
                                    contentDescription = "Local Image", // Description for accessibility
                                    modifier = Modifier
                                        .align(Alignment.CenterVertically) // Align the image vertically within the row
                                )
                            }
                        }
                        if (showPopup.value) {
                            Popup1(showPopup)
                        }
                    }
                    Spacer(modifier = Modifier.height(30.px))
                    Box(modifier = Modifier.fillMaxSize()) {
                        ProductList()
                        if (showPopup.value) {
                            Box(
                                modifier = Modifier
                                    .fillMaxSize()
                                    .background(Color.Black.copy(alpha = 0.5f))
                            )
                        }
                    }

                }
            }
        }
    }

    @Composable
    fun Popup1(showPopup: MutableState<Boolean>) {
        val selected1 = remember { viewModel.interests }
        val selected2 = remember { mutableStateOf("全部") }
        val names by viewModel.question3List.collectAsState()
        val names2: List<HouseType> by viewModel.question2List.collectAsState()
        Popup(
            alignment = Alignment.TopStart,
            offset = IntOffset(1 * 30, 1 * 80),
            onDismissRequest = { showPopup.value = false }) {
            Card(modifier = Modifier
                .width(1206.px)
                .wrapContentHeight(),
                shape = RoundedCornerShape(40.px),
                colors =  CardDefaults.cardColors(containerColor = Color.White)

            ) {
                Column(
                    modifier = Modifier
                        .fillMaxWidth()
                        .wrapContentHeight()
                        .padding(30.px)
//                        .offset(y = 10.dp, x = 10.dp)
                )
                {
                    Row(verticalAlignment = Alignment.CenterVertically) {
                        Text(text = "适用喜好", fontSize = MyFont_Size)
                        names2.forEach {
                            Spacer(modifier = Modifier.width(6.dp))
                            TwoStateButton(selected1, "${it.name}"){ _->
                                viewModel.interestsCode.value = it.code;
                            }
                        }
                    }
                    Spacer(modifier = Modifier.height(4.dp))
                    Row(verticalAlignment = Alignment.CenterVertically) {
                        Spacer(modifier = Modifier.width(14.dp))
                        Text(text = "材料", fontSize = MyFont_Size)
                        Spacer(modifier = Modifier.width(20.px))
                        // Grid Section
                        LazyVerticalGrid(
                            verticalArrangement = Arrangement.spacedBy(20.px), // 行间距
                            horizontalArrangement = Arrangement.spacedBy(20.px), // 列间距
                            columns = GridCells.Fixed(5), // Set columns based on desired layout
//                            modifier = Modifier.height(100.dp) // Set appropriate height for the grid
                        ) {
                            items(names) { item ->
                                Spacer(modifier = Modifier.width(6.dp))
                                TwoStateButton(selected2, item.name) {
                                    // Handle button click here
                                }
                            }
                        }
                    }
                    Spacer(modifier = Modifier.height(30.px))
                    Row(
                        verticalAlignment = Alignment.CenterVertically,
                        modifier = Modifier
                            .fillMaxWidth()
                            .background(Color.White)
                            .wrapContentWidth(Alignment.CenterHorizontally)
                    ) {
                        MyButton01(
                            text = "重置",
                            containerColor = MYBLACK_Percent5,
                            textColor = Color.Black,
                                    shape = RoundedCornerShape(6.px),
                        ) {
                            selected1.value = "全部"
                            selected2.value = "全部"
                            viewModel.interestsCode.value = ""
                        }
                        Spacer(modifier = Modifier.width(20.dp))
                        MyButton01(
                            shape = RoundedCornerShape(6.px),
                            text = "确认",containerColor= MYBLUE,textColor=Color.White){
                            showPopup.value = false
                            viewModel.loadMoreData()
                        }
                    }
//                    Spacer(modifier = Modifier.height(30.px))
                }
            }
        }
    }

    @Composable
    fun RowWithShapeBox() {
        // State to keep track of the current image resource
        // Define two images to switch between
        val up = painterResource(id = R.drawable.up) // Replace with your first image resource
        val down = painterResource(id = R.drawable.down) // Replace with your second image resource

        // Current image to display based on the toggle state
        val currentImage = if (viewModel.isToggled.value) up else down

        Box(
            modifier = Modifier
                .offset(x = 30.px)
                .size(122.px, 50.px)
                .clickable {
                    viewModel.isToggled.value = viewModel.isToggled.value.not()
                    viewModel.loadMoreData()
                }
//                    .padding(16.dp)
                .background(
                    MYBLACK_Percent5,
                    shape = RoundedCornerShape(25)
                ) // Apply shape with background
        ) {
            Row(modifier = Modifier.align(Alignment.Center)) {
                BasicText(
                    text = "价格",
                    style = TextStyle(
                        fontSize =MyFont_Size,
                        color = MYBLACK,
                    )
                )
                Spacer(modifier = Modifier.width(3.dp))
                Image(
                    painter = currentImage, // Replace with your image resource
                    contentDescription = "Local Image", // Description for accessibility
                    modifier = Modifier
//                            .size(24.dp) // Set the size of the image
                        .align(Alignment.CenterVertically) // Align the image vertically within the row
                )
            }
        }
    }

    @OptIn(ExperimentalGlideComposeApi::class)
    @Composable
    fun ProductList() {
        // 观察 LiveData
        val items: List<DataB> by viewModel.dataList.collectAsState()

        SystemFragmentBackground2(topStart=40.px) {
            if (items.size == 0) {
                Column(
                    modifier = Modifier.fillMaxSize(),
                    horizontalAlignment = Alignment.CenterHorizontally,
                    verticalArrangement = Arrangement.Center
                ) {
                    GlideImage(
                        model = R.drawable.empty,
                        contentDescription = "",
                    )
                    Spacer(modifier = Modifier.height(30.px))
                    BasicText(
                        maxLines = 1,
                        overflow = TextOverflow.Clip,
                        text = "暂无数据",
                        style = TextStyle(
                            fontSize = 30.mysp,
                            color = MYBLACK,
                        )
                    )
                }
                return@SystemFragmentBackground2
            }

            LazyVerticalGrid(
                verticalArrangement = Arrangement.spacedBy(30.px), // 可以设置垂直间隔，例如16dp
                horizontalArrangement = Arrangement.spacedBy(20.px), // 水平间隔设置为 20px
                columns = GridCells.Fixed(6), // 2 columns in the grid
                modifier = Modifier
                    .fillMaxSize()
                    .padding(
                        start = 30.px,
                        end = 30.px,
                        top = 30.px,
                        bottom = 30.px
                    )
//                    .padding((30/3.5f).dp)
            ) {
                items(items) { item ->
                    ProductItem(item)
                }
            }
        }
    }

    @OptIn(ExperimentalGlideComposeApi::class)
    @Composable
    fun ProductItem(item:DataB) {
        Card(
            colors = androidx.compose.material3.CardDefaults.cardColors(
                containerColor = MYBLACK_Percent5 // 设置背景色为红色
            ),
            shape = RoundedCornerShape(
                topEnd = 10.px,
                topStart = 10.px,
                bottomStart = 14.px,
                bottomEnd = 14.px,
            ),
            modifier = Modifier
                .background(Color.Transparent)
                .width(284.px)
                .wrapContentHeight()
        ) {
            Column(
                modifier = Modifier
                    .align(Alignment.CenterHorizontally)
                    .padding(0.px)
            ) {
                GlideImage(
                    model = item.thumbnail,
                    contentDescription ="",
                    modifier = Modifier
                        .align(Alignment.CenterHorizontally)
                        .size(284.px, 284.px)
                        .clickable {
                            startActivity<XiangQingActivity>() {
                                putExtra("id", item.id)
                            }
                        },
                )
                Spacer(modifier = Modifier.height(20.px))
                Row(
                    verticalAlignment = Alignment.Bottom,
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(start = 20.px, end = 20.px),
                    horizontalArrangement = Arrangement.Start
                ) {
                    Column {
//                    Log.e(TAG,""+item.name)
                        Text(
                            text = item.name, color = Color.Black, fontSize = (24 / 3.5f).sp,
                            modifier = Modifier.width(170.px),  // 限制宽度为 100px (100.dp)
                            maxLines = 1,  // 限制为单行
                            overflow = TextOverflow.Ellipsis  // 超出宽度时显示省略号
                        )
                        Spacer(modifier = Modifier.height(10.px))
                        Row {
//                            BasicText(
//                                text = "¥",
//                                style = TextStyle(
//                                    fontSize = 16.mysp,
//                                    color = MYBLUE,
//                                    textAlign = TextAlign.Center,
//                                ),
//                            )
                            BasicText(
                                text = "¥" + item.price+"/"+item.unitName,
                                style = TextStyle(
                                    fontSize = MyFont_Size,
                                    color = MYBLUE,
                                    textAlign = TextAlign.Center,
                                    fontWeight = FontWeight.Bold
                                ),
                            )
                        }
                    }
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.e(TAG, "onDestroy")
    }

    companion object {
        const val TAG = "ShangPinKuActivity"
    }
}

